package com.ls.common.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ls.common.entity.Result;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author konglz
 * @Data 2023/4/28 11:54
 */
@Component
public class MyBlockException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        // 打印异常信息
        e.printStackTrace();
        // 返回数据
        Result result = new Result(400, "接口被限流了(统一异常处理)===哈哈哈");
        response.setStatus(400);// 设置响应状态
        response.setCharacterEncoding("UTF-8");// 设置编码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);// 设置响应的数据类型
        new ObjectMapper().writeValue(response.getWriter(), result);// 设置响应数据
    }
}
